//
//  My_EditInfoViewController.m
//  XDBaseFrameWork
//
//  Created by wanglong8889@126.com on 14-9-29.
//  Copyright (c) 2014年 XD-XY. All rights reserved.
//

#import "My_EditInfoViewController.h"

#import "EditInfoTableViewCell.h"

#import "ChangeNIckeViewController.h"

#import "EditCommentViewController.h"

#import "UIImageView+WebCache.h"

@interface My_EditInfoViewController ()

@end

@implementation My_EditInfoViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.titleLabel.text = @"编辑个人信息";
    
    [self initEditInfoViews];
    
}

-(void)initEditInfoViews{
    
    myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 15, UI_SCREEN_WIDTH, self.contentView.frame.size.height-15) style:UITableViewStylePlain];
    myTableView.delegate = self;
    myTableView.dataSource = self;
    myTableView.backgroundColor = [UIColor clearColor];
    
    dataArry = [[NSArray alloc] initWithObjects:@"我的头像",@"我的昵称",@"宝宝性别",@"宝宝生日", nil];
    
    headView = [[UIImageView alloc] initWithFrame:CGRectMake(UI_SCREEN_WIDTH-10-70,6, 140/2, 140/2)];
    
    headView.backgroundColor = UIColorFromRGB(0xeaeaea);
    [headView sd_setImageWithURL:[NSURL URLWithString:[[NSUserDefaults standardUserDefaults] valueForKey:kMY_USER_FACE]] placeholderImage:nil];
    
    myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    headView.layer.masksToBounds = YES;
    headView.layer.cornerRadius = 35;
    headView.layer.rasterizationScale = [UIScreen mainScreen].scale;
    headView.layer.shouldRasterize   = YES;
    headView.clipsToBounds = YES;
    headView.contentMode = UIViewContentModeScaleAspectFill;//跟微信一样 填充
    
    // UIViewContentModeScaleToFill,
   // UIViewContentModeScaleAspectFit,
   // UIViewContentModeScaleAspectFill,
    
    [self.contentView addSubview:myTableView];
    
    resultDic = [[NSDictionary alloc] init];
    
    
    customId = [[NSUserDefaults standardUserDefaults] objectForKey:kMY_USER_ID];
    
    if (customId == nil) {
        customId = @"";
    }
    
    [self getUserInfoDatas];
    
    datePicker = [[UIDatePicker alloc]init];
    datePicker.frame = CGRectMake(0, UI_SCREEN_HEIGHT, UI_SCREEN_WIDTH, 260);
    datePicker.datePickerMode = UIDatePickerModeDate;
    NSDateComponents *comp = [[NSDateComponents alloc]init];
    [comp setMonth:01];
    [comp setDay:01];
    [comp setYear:2010];
    NSCalendar *myCal = [[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];
    NSDate *minDate = [myCal dateFromComponents:comp];
    NSDateComponents *comptwo = [[NSDateComponents alloc]init];
    [comptwo setMonth:12];
    [comptwo setDay:31];
    [comptwo setYear:2016];
    NSCalendar *myCalTwo = [[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];
    NSDate *maxDate = [myCalTwo dateFromComponents:comptwo];
//    datePicker.maximumDate = maxDate;
//    datePicker.minimumDate = minDate;
    [datePicker addTarget:self action:@selector(datePickerValueChange) forControlEvents:UIControlEventValueChanged];
    [self.contentView addSubview:datePicker];
    
    UIButton  * finishButton = [UIButton buttonWithType:UIButtonTypeCustom];
    finishButton.frame =  CGRectMake(10, 5, 40, 30);
    [finishButton setTitle:@"完成" forState:UIControlStateNormal];
    [finishButton addTarget:self action:@selector(finishButtonPressed) forControlEvents:UIControlEventTouchUpInside];
    finishButton.titleLabel.textColor = [UIColor blackColor];
    assoryView = [[UIView alloc]initWithFrame:CGRectMake(0, UI_SCREEN_HEIGHT-40, UI_SCREEN_WIDTH, 40)];
    assoryView.backgroundColor = [UIColor orangeColor];
    [assoryView addSubview:finishButton];
    [self.contentView addSubview:assoryView];
    
    
}



#pragma  tableview 代理方
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 4;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *cellIdentifer = @"editInfoCell";
    
    EditInfoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifer];
    
    if (!cell) {
        cell = [[EditInfoTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifer];
        
        cell.textLabel.text = [dataArry objectAtIndex:indexPath.row];
        cell.textLabel.font = [UIFont systemFontOfSize:15.0];
//        cell.textLabel.textColor = [UIColor blackColor];

        
    }
    
    if (indexPath.row == 0) {
        [cell addSubview:headView];
        
        cell.upLineView.frame = CGRectMake(0,0, UI_SCREEN_WIDTH, .5);
        cell.downLineView.frame = CGRectMake(13,80-.5, UI_SCREEN_WIDTH-13, .5);
        cell.contentLabel.hidden = YES;
        cell.arrowView.hidden = YES;
        cell.downLineView.hidden = NO;
        cell.upLineView.hidden = NO;
        
        
        NSString *headUrl = [NSString stringWithFormat:@"http://182.92.172.33/PhotoView.ashx?pid=%@",[resultDic objectForKey:@"Photo"]];
        
        [headView sd_setImageWithURL:[NSURL URLWithString:headUrl] placeholderImage:[UIImage imageNamed:@"placeholderHeader"]];
    }else{
        cell.upLineView.hidden = YES;
        cell.downLineView.hidden = NO;
        
        if (indexPath.row == 1) {
            cell.contentLabel.text = [resultDic  objectForKey:@"NickName"];
        }else if (indexPath.row == 2){
            if ([[resultDic objectForKey:@"BabyGend"] isEqualToString:@"M"]) {
                 cell.contentLabel.text = @"男";
            }else if ([[resultDic objectForKey:@"BabyGend"] isEqualToString:@"F"]){
                cell.contentLabel.text = @"女";
            }else{
               cell.contentLabel.text = @"";
            }
        }else{
            cell.downLineView.frame = CGRectMake(0, 43-.5, UI_SCREEN_WIDTH, .5);
            cell.contentLabel.text = [resultDic objectForKey:@"BabyBirthday"];
            requestDateString = [resultDic objectForKey:@"BabyBirthday"];

        }
        
    }
    
    return cell;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        return 80;
    }else{
        return 43;
    }
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
     EditInfoTableViewCell *cell = (EditInfoTableViewCell *)[myTableView cellForRowAtIndexPath:indexPath];
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.row == 0) {
        //换头像
        UIActionSheet* sheet1 = [[UIActionSheet alloc] initWithTitle:nil delegate:self
                                                  cancelButtonTitle:@"取消"
                                             destructiveButtonTitle:nil
                                                  otherButtonTitles:@"相机",@"从相册选择",nil];
        
        sheet1.tag = 100;
        [sheet1 showInView:[self view]];
    }else if(indexPath.row == 1){
        //去昵称
        
        ChangeNIckeViewController *nickerVC = [[ChangeNIckeViewController alloc] init];
        
        nickerVC.name = cell.contentLabel.text;
        
        nickerVC.editVC = self;
        
        [self.navigationController pushViewController:nickerVC animated:YES];
        
    }else if (indexPath.row == 2){
        //选择性别
        
        UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:@"选择性别" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"男",@"女", nil];
        
        sheet.tag = 101;
        

        [sheet showInView:self.view];
    }else{
        [UIView animateWithDuration:.5f animations:^{
            datePicker.frame = CGRectMake(0, UI_SCREEN_HEIGHT-260, UI_SCREEN_WIDTH, 260);
            assoryView.frame = CGRectMake(0, UI_SCREEN_HEIGHT-260-40, UI_SCREEN_WIDTH, 40);
        }];
    }
}

-(void)finishButtonPressed
{
    [UIView animateWithDuration:0.3 animations:^{
        datePicker.frame = CGRectMake(0, UI_SCREEN_HEIGHT, UI_SCREEN_WIDTH, 260);
        assoryView.frame = CGRectMake(0, UI_SCREEN_HEIGHT-40, UI_SCREEN_WIDTH, 40);
    }];
    
    ///把生日换掉就行了
    
    EditInfoTableViewCell *cell = (EditInfoTableViewCell *)[myTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:3 inSection:0]];
    if (![requestDateString isEqualToString:cell.contentLabel.text]) {
        NSDictionary *requestDic = @{@"CustomerID":customId,
                                     @"BabyBirthday":cell.contentLabel.text};
        [self editInfosData:requestDic];
    }
    
}

#pragma  代理方法

- (void)willPresentActionSheet:(UIActionSheet *)actionSheet

{
    
    if (actionSheet.tag == 101 ) {
        for (UIView *subViwe in actionSheet.subviews) {
            
            if ([subViwe isKindOfClass:[UIButton class]]) {
                
                UIButton *button = (UIButton*)subViwe;
                
                if ([button.titleLabel.text isEqualToString:@"取消"]) {
                    [button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
                }
                
                
                
            }
            
        }
    }
    
    
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
     EditInfoTableViewCell *cell = (EditInfoTableViewCell *)[myTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:0]];
    
    if (actionSheet.tag == 101) {
        if (buttonIndex == 0) {
            if (![cell.contentLabel.text isEqualToString:@"男"]) {
                cell.contentLabel.text = @"男";
                NSDictionary *requestDic = @{@"CustomerID":customId,
                                             @"BabyGend":@"M"};
                [self editInfosData:requestDic];
            
                
                
                
            }
            
        }else if(buttonIndex == 1) {
            if (![cell.contentLabel.text isEqualToString:@"女"]){
                cell.contentLabel.text = @"女";
                NSDictionary *requestDic = @{@"CustomerID":customId,
                                             @"BabyGend":@"F"};
                [self editInfosData:requestDic];
            }
            
        }
        
       
    }else if (actionSheet.tag == 100){
        if(buttonIndex ==0){
            [self choseImageWithTypeCameraTypePhotoLibrary:UIImagePickerControllerSourceTypeCamera];
        }else if(buttonIndex == 1){
            [self choseImageWithTypeCameraTypePhotoLibrary:UIImagePickerControllerSourceTypePhotoLibrary];
        }
    }
    
}


-(void)choseImageWithTypeCameraTypePhotoLibrary:(UIImagePickerControllerSourceType)type{
    UIImagePickerController * imagePicker = [[UIImagePickerController alloc] init];
    
    imagePicker.delegate =self;
    imagePicker.sourceType = type;
    
    imagePicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    
    imagePicker.allowsEditing =YES;
    [self presentViewController:imagePicker animated:YES completion:^{
        
    }];
}




#pragma mark xuan ze zhao pian de dai li
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
    {
        DDLOG(@"%@",info);
        UIImage *image = [info objectForKey:@"UIImagePickerControllerEditedImage"];
        NSData * imageData = UIImageJPEGRepresentation(image,0.6);
        
        NSString * timeSp = [NSString stringWithFormat:@"%ld.jpg", (long)[[NSDate date] timeIntervalSince1970]];
 
        NSString *requestUrl = [NSString stringWithFormat:@"http://182.92.172.33/Upx.ashx?PTX=%@&SID=%@",@"CustomerPhoto",customId];
        headView.image = image;
        if (![XDTools NetworkReachable]){
            [XDTools showTips:brokenNetwork toView:self.view];
            
            return;
        }

        
        ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:requestUrl]];
        
        [request setRequestMethod:@"POST"];
        [request setPostValue:customId forKey:@"CustomerID"];
        [request setTimeOutSeconds:15];

        [request addData:imageData withFileName:timeSp andContentType:@"image/jpeg" forKey:@"img"];
        

        
        
        __weak ASIFormDataRequest * mrequest = request;
        

        [request setCompletionBlock:^{
            [XDTools hideProgress:self.contentView];
            NSDictionary *resultDictionary = [XDTools JSonFromString:[mrequest responseString]];
            DDLOG(@"res....%@",resultDictionary);
            if ([[resultDictionary objectForKey:@"Succeed"] intValue]==1) {
                [[NSUserDefaults standardUserDefaults] setValue:resultDictionary[@"Result"] forKey:kMY_USER_FACE];
               [XDTools showTips:@"上传成功！" toView:self.view];
            }else{
                [XDTools showTips:[resultDictionary objectForKey:@"Error"] toView:self.view];
            }
        }];
        [request setFailedBlock:^{
            [XDTools hideProgress:self.contentView];
            if (mrequest.error.code == 2) {
                [XDTools showTips:@"网络请求超时" toView:self.contentView];
            }
        }];
        [request startAsynchronous];
        [XDTools showProgress:self.contentView showText:@"正在上传图片"];
        
        [picker dismissViewControllerAnimated:YES completion:^{
        }];
        
    }

    //对图片尺寸进行压缩--
-(UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize
    {
        // Create a graphics image context
        UIGraphicsBeginImageContext(newSize);
        
        // Tell the old image to draw in this new context, with the desired
        // new size
        [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
        
        // Get the new image from the context
        UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
        
        // End the context
        UIGraphicsEndImageContext();
        
        // Return the new image.
        return newImage;
    }
    //- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    //
    //}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
        [picker dismissViewControllerAnimated:YES completion:^{
            
        }];
    }



// 编辑个人资料接口
-(void)editInfosData:(NSDictionary *)dic{
    if(![XDTools NetworkReachable]){
        [XDTools showTips:brokenNetwork toView:self.contentView];
        return;
    }
    
    EditInfoTableViewCell *cell = (EditInfoTableViewCell *)[myTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
    
    
    NSString * nickName = [dic objectForKey:@"NickName"];
    if (nickName!=nil) {
        cell.contentLabel.text = nickName;
    }else{
        nickName = cell.contentLabel.text;
    }
    
    ASIHTTPRequest *request = [XDTools postRequestWithDict:dic API:API_UPDATEINFO];
    __weak ASIHTTPRequest * mrequest = request;
    [request setCompletionBlock:^{
        NSDictionary *resultDictionary = [XDTools JSonFromString:[mrequest responseString]];
        DDLOG(@"res....%@",resultDictionary);
        if ([[resultDictionary objectForKey:@"status"] intValue]==1) {
            [[NSUserDefaults standardUserDefaults] setValue:nickName forKey:kMY_USER_NAME];
        }else{
            [XDTools showTips:[resultDictionary objectForKey:@"msg"] toView:self.contentView];
        }
    }];
    [request setFailedBlock:^{
        [XDTools hideProgress:self.contentView];
        if (mrequest.error.code == 2) {
            [XDTools showTips:@"网络请求超时" toView:self.view];
        }
    }];
    [request startAsynchronous];
}

//获取个人资料

-(void)getUserInfoDatas
{
    if(![XDTools NetworkReachable]){
        [XDTools showTips:brokenNetwork toView:self.contentView];
        return;
    }
    

    NSDictionary *requestDic = @{@"CustomerID": customId};
    ASIHTTPRequest *request = [XDTools postRequestWithDict:requestDic API:API_PERSONINFO];
    __weak ASIHTTPRequest * mrequest = request;
    [request setCompletionBlock:^{
        NSDictionary *resultDictionary = [XDTools JSonFromString:[mrequest responseString]];
        DDLOG(@"res....%@",resultDictionary);
        if ([[resultDictionary objectForKey:@"status"] intValue]==1) {
            
            resultDic = [resultDictionary objectForKey:@"data"];
            [myTableView reloadData];
        }else{
            [XDTools showTips:[resultDictionary objectForKey:@"msg"] toView:self.contentView];
        }
    }];
    [request setFailedBlock:^{
        [XDTools hideProgress:self.contentView];
        if (mrequest.error.code == 2) {
            [XDTools showTips:@"网络请求超时" toView:self.view];
        }
    }];
    [request startAsynchronous];
}


-(void)datePickerValueChange
{
    [self getDateString];
}
-(void)getDateString
{
    NSDateFormatter* dateFormat = [[NSDateFormatter alloc] init];//实例化一个NSDateFormatter对象
    [dateFormat setDateFormat:@"yyyy-MM-dd"];
    NSString *  locationString = [dateFormat stringFromDate:datePicker.date];
    
     EditInfoTableViewCell * cell = (EditInfoTableViewCell *)[myTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:3 inSection:0]];
    cell.contentLabel.text = locationString;
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
